<template>
  <div class="projectQuote" v-loading="pageLoading">
    <header class="flex-align-center">
      <!-- <span class="blueLine"></span>
      <span style="margin-left: 10px">工程报价</span>-->
      <el-button style="margin-left: 20px" @click="cancelBtn" size="mini">返回</el-button>
      <div class="absolute" style="float: right; right: 36px" v-if="!echo">
        <el-button type="success" size="mini" @click="tempStore">暂存</el-button>
        <el-button type="primary" size="mini" @click="submitForm">提交</el-button>
      </div>
    </header>
    <main v-if="dataInfo">
      <!-- <div class="demandIdBox">需求单号: {{$route.query.id}}</div> -->
      <div class="demandIdBox">工程报价</div>
      <div class="infoBox" style="margin-top: 0">
        <el-descriptions title="基本信息" :column="4">
          <el-descriptions-item
            v-for="(item, index) in baseInfo"
            :key="'baseInfo' + index"
            :label="item.name"
          >
            <span v-if="item.key=='shippingRequirement'">
              <em v-if="dataInfo[item.key]=='1'">散货出</em>
              <em v-else-if="dataInfo[item.key]=='2'">栈板出</em>
              <em v-else-if="dataInfo[item.key]=='3'">静电箱出</em>
              <em v-else-if="dataInfo[item.key]=='4'">周转箱出</em>
              <em v-else>无</em>
            </span>
            <span v-else>{{ dataInfo[item.key] || (item.key == 'value' ? "字段暂无" : "无")}}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="infoBox">
        <el-descriptions title="产品信息" :column="4">
          <el-descriptions-item
            v-for="(item, index) in productInfo"
            :key="'productInfo' + index"
            :label="item.name"
            :labelStyle="{display: 'flex'}"
          >
            <span v-if="item.type == 'array'">
              <template v-for="(it, ind) in dataInfo[item.key]">
                <el-tag style="margin-right: 10px" :key="'asdfg' + ind" size="medium">{{ it }}</el-tag>
              </template>
            </span>
            <span v-else-if="item.type == 'object'">
              <template v-for="(its, inds) in Object.keys(dataInfo[item.key])">
                <el-tag
                  style="margin-right: 10px"
                  :key="'asdfg' + inds"
                  size="medium"
                >{{ its }} : {{ dataInfo[item.key][its] ? dataInfo[item.key][its] + ' ‰' : '无'}}</el-tag>
              </template>
            </span>
            <span v-else-if="item.type == 'downLoad'">
              <template v-for="(it, ind) in dataInfo[item.key]">
                <DownLoadFiles
                  :key="'dowmLoadFiles' + ind"
                  style="margin-right: 40px"
                  :url="it.url"
                  :title="it.name"
                ></DownLoadFiles>
              </template>
              <span v-if="!dataInfo[item.key].length">未上传</span>
            </span>
            <span v-else>{{ dataInfo[item.key] || (item.key == 'value' ? "字段暂无" : "无") }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="infoBox">
        <el-descriptions title :column="2">
          <el-descriptions-item
            v-for="(item, index) in productInputInfo"
            :key="'productInputInfo' + index"
            :label="item.name"
            :labelStyle="{display: 'flex'}"
            :labelClassName="item.mandatory ? 'setred' : ''"
          >
            <span v-if="item.type == 'upload'">
              <template v-if="!echo">
                {{ bomFileName }}
                <FileUpload :typeName="item.key" @FileList="uploadFile" :id="dataInfo.id"></FileUpload>
              </template>
              <template v-else>
                <DownLoadFiles
                  v-if="dataInfo[item.key].url"
                  style="margin-right: 40px"
                  :url="dataInfo[item.key].url"
                  :title="dataInfo[item.key].name"
                ></DownLoadFiles>
              </template>
            </span>
            <span v-else class="flex">
              <template v-if="!echo">
                <el-input style="width: 360px" v-model="dataInfo[item.key]" size="mini" :placeholder="item.placeholder"></el-input>
                <span style="margin-left: 10px;" class="flex-align-center" v-if="item.unit">{{ item.unit }}</span>
              </template>
              <template v-else>
                {{ dataInfo[item.key] }}{{ item.unit }}
              </template>
              <!-- <template v-else>{{ dataInfo[item.key] }}</template> -->
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="infoBox">
        <el-descriptions title="效率清单" :column="1" :colon="false">
          <el-descriptions-item>
            <el-table :data="processItem" border style="width: 1200px">
              <el-table-column prop="projectName" label="工段" align="center"></el-table-column>
              <el-table-column label="效率" align="center">
                <template slot-scope="scope">
                  <template v-if="!echo">
                    <span v-if="scope.row.inputArgument.unit === '件'">{{ (scope.row.inputArgument.efficiency || '0') + ' 件' }}</span>
                    <!-- <span v-else-if="scope.row.inputArgument.unit === '片'">{{scope.row.inputArgument.efficiency || 0}} 片</span> -->
                    <checkInput v-else-if="scope.row.inputArgument.unit === '小时' || scope.row.inputArgument.unit === '片'" :inValue.sync="scope.row.inputArgument.efficiency"
                      :prop="{
                        type: 'number',
                        precision: 0,
                        fill: true,
                        unit: '秒',
                        placeholder: '',
                        range: [0, 999999999]
                      }"
                      ></checkInput>
                    <checkInput v-else :inValue.sync="scope.row.inputArgument.efficiency"
                      :prop="{
                        type: 'number',
                        precision: 0,
                        fill: true,
                        unit: scope.row.inputArgument.unit,
                        placeholder: '',
                        range: [0, 999999999]
                      }"
                      ></checkInput>
                  </template>
                  <span v-else>{{ scope.row.inputArgument.efficiency }}</span>
                  <!-- {{ scope.row.unit }} -->
                </template>
              </el-table-column>
              <el-table-column label="线体人员投入" align="center">
                <template slot-scope="scope">
                  <!-- <el-input
                    v-if="!echo"
                    v-model="scope.row.inputArgument.employeeInput"
                    size="mini"
                  ></el-input> -->
                  <checkInput v-if="!echo" :inValue.sync="scope.row.inputArgument.employeeInput"
                  :prop="{
                    type: 'number',
                    precision: 0,
                    fill: true,
                    unit: '',
                    placeholder: '',
                    integer: true,
                    range: [0, 999999999]
                  }"
                  ></checkInput>
                  <span v-else>{{ scope.row.inputArgument.employeeInput }}</span>
                </template>
              </el-table-column>
              <el-table-column label="小时产能（pcs）" align="center">
                <template slot-scope="scope">
                  <!-- <el-input v-if="!echo" v-model="scope.row.inputArgument.hourOutput" size="mini"></el-input> -->
                  <template v-if="!echo">
                    <!-- <span v-if="processItemUnit[scope.$index] === '小时'">{{ scope.row.inputArgument.hourOutput || 0 }}</span> -->
                    <checkInput :inValue.sync="scope.row.inputArgument.hourOutput"
                    :prop="{
                      type: 'number',
                      precision: 0,
                      fill: true,
                      unit: '',
                      placeholder: '',
                      integer: true,
                      range: [0, 999999999]
                    }"
                    ></checkInput>
                  </template>

                  <span v-else>{{ scope.row.inputArgument.hourOutput }}</span>
                </template>
              </el-table-column>
              <el-table-column label="效率预测" align="center">
                <template slot-scope="scope">
                  <template v-if="!echo">
                    <!-- <el-input
                      style="width: 90%"
                      v-model="scope.row.inputArgument.predictEfficiency"
                      size="mini"
                    ></el-input> -->
                    <checkInput v-if="!echo" :inValue.sync="scope.row.inputArgument.predictEfficiency"
                    :prop="{
                      type: '',
                      precision: 0,
                      fill: true,
                      unit: '%',
                      placeholder: '',
                      integer: false,
                      range: [0, 100]
                    }"
                    ></checkInput>
                  </template>
                  <span v-else>{{ scope.row.inputArgument.predictEfficiency }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="infoBox">
        <el-descriptions title="工程开机费" :column="1" :colon="false">
          <el-descriptions-item>
            <el-table :data="machineItem" border style="width: 1200px">
              <el-table-column prop="projectName" label="工段" align="center"></el-table-column>
              <el-table-column label="参与人数" align="center">
                <template slot-scope="scope">
                  <!-- <el-input
                    v-if="!echo"
                    v-model="scope.row.inputArgument.employeeInput"
                    size="mini"
                  ></el-input> -->
                  <checkInput v-if="!echo" :inValue.sync="scope.row.inputArgument.employeeInput"
                    :prop="{
                      type: 'number',
                      precision: 0,
                      fill: true,
                      unit: '',
                      placeholder: '',
                      integer: true,
                      range: [0, 99999999]
                    }"
                    ></checkInput>
                  <span v-else>{{ scope.row.inputArgument.employeeInput }}</span>
                </template>
              </el-table-column>
              <el-table-column label="每人耗时 (小时)" align="center">
                <template slot-scope="scope">
                  <!-- <el-input
                    v-if="!echo"
                    v-model="scope.row.inputArgument.employeeTimeCost"
                    size="mini"
                  ></el-input> -->
                  <checkInput v-if="!echo" :inValue.sync="scope.row.inputArgument.employeeTimeCost"
                    :prop="{
                      type: 'number',
                      precision: 2,
                      fill: true,
                      unit: '',
                      placeholder: '',
                      integer: false,
                      range: [0, 99999999]
                    }"
                    ></checkInput>
                  <span v-else>{{ scope.row.inputArgument.employeeTimeCost }}</span>
                </template>
              </el-table-column>
              <el-table-column label="总耗时 (小时)" align="center">
                <template
                  slot-scope="scope"
                >{{ scope.row.inputArgument.employeeTimeCost * scope.row.inputArgument.employeeInput || 0 }}</template>
              </el-table-column>
            </el-table>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="infoBox">
        <el-descriptions title="辅料清单" :column="1" :colon="false">
          <el-descriptions-item>
            <el-table
              ref="fixtureMultipleTable"
              :data="dataInfo.assistMaterialItem"
              border
              current-row-key="materialNumber"
              style="width: 1400px"
              tooltip-effect="dark"
              :height="echo ? 'auto' : '650px'"
              @select="handleSelect"
            >
              <el-table-column type="selection" width="55" v-if="!echo"></el-table-column>
              <el-table-column label="物料编码">
                <template slot-scope="scope">
                  <span>{{ scope.row.materialNumber }}</span>
                </template>
              </el-table-column>
              <el-table-column label="物料名称">
                <template slot-scope="scope">
                  <span>{{ scope.row.materialName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="规格型号">
                <template slot-scope="scope">
                  <span>{{ scope.row.description }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单位" width="100">
                <template slot-scope="scope">
                  <span>{{ scope.row.capacityUnit }}</span>
                </template>
              </el-table-column>
              <el-table-column label="总量">
                <template slot-scope="scope">
                  <span>{{ scope.row.capacityVolume }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单价">
                <template slot-scope="scope">
                  <template>
                    <!-- <el-input size="mini" v-model="scope.row.materialPrice" placeholder="请输入单价" @blur="computedAsistPrice(scope.row, scope.$index)"></el-input> -->
                    <span v-if="!scope.row.price">--</span>
                    <span v-else-if="!scope.row.capacityVolume">--</span>
                    <span v-else>{{ (scope.row.price / scope.row.capacityVolume ).toFixed(5) }}</span>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="用量">
                <template slot-scope="scope">
                  <!-- <el-input
                    v-if="!echo"
                    size="mini"
                    v-model="scope.row.materialUse"
                    placeholder="请输入用量"
                    @blur="computedAsistPrice(scope.row, scope.$index)"
                  ></el-input> -->
                  <checkInput v-if="!echo && scope.row.select" :inValue.sync="scope.row.materialUse"
                    @inputChange="inputChange"
                    :otherProp="[scope.row, scope.$index]"
                    :prop="{
                      type: 'number',
                      precision: 4,
                      fill: true,
                      unit: '',
                      placeholder: '',
                      integer: false,
                      range: [0, 99999999]
                    }"
                    ></checkInput>
                  <span v-else>{{ scope.row.materialUse }}</span>
                </template>
              </el-table-column>
              <el-table-column label="用量单位">
                <template slot-scope="scope">
                  <!-- <el-input v-if="!echo" size="mini" v-model="scope.row.materialTotal" placeholder="请输入用量单位" @blur="computedAsistPrice(scope.row, scope.$index)"></el-input> -->
                  <span>{{ scope.row.capacityUnit }}</span>
                </template>
              </el-table-column>
              <el-table-column label="金额">
                <template slot-scope="scope">
                  <span>{{ scope.row.amount }}</span>
                </template>
              </el-table-column>
            </el-table>
            <div>
              <el-tag style="float: right; margin: 10px 0 0 0">小计: {{ machineTotalPrice }} 元</el-tag>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="infoBox">
        <el-descriptions title="工治具费用" :column="1" :colon="false">
          <el-descriptions-item>
            <div class="flex">
              <!-- <div class="fixtureLeft">
                <div>分类对照表</div>
                <div v-for="item in mapList" :key="item">{{ item }}</div>
              </div>-->
              <div class="fixtureRight">
                <el-table
                  :data="fixture"
                  border
                  style="width: 1400px"
                  ref="JSMultipleTable"
                  :span-method="objectSpanMethod"
                  @row-click="openEdit"
                >
                  <el-table-column label="分类" :align="'center'" prop="category" width="180"></el-table-column>
                  <el-table-column label="物料编码" width="350">
                    <template slot-scope="scope">
                      <template v-if="fixtureIndex == scope.$index">
                        <el-select
                          style="width: 100%"
                          v-model="fixture[scope.$index]"
                          filterable
                          remote
                          reserve-keyword
                          placeholder="请输入物料编码"
                          :remote-method="remoteFixtureMethod"
                          :loading="loading"
                          size="mini"
                          @focus="openEditItem(scope.$index, scope.row)"
                          @change="deleteList"
                        >
                          <el-option
                            v-for="(item, index) in fixtureOptions"
                            :key="index + 'maps131'"
                            :label="item.materialNumber + '  ' + item.materialName"
                            :value="item"
                          ></el-option>
                        </el-select>
                      </template>
                      <span v-else>{{ scope.row.materialNumber }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="名称" width="250">
                    <template slot-scope="scope">
                      <span>{{ scope.row.materialName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="单价">
                    <template slot-scope="scope">
                      <template v-if="fixtureIndex == scope.$index">
                        <el-input size="mini" v-model="scope.row.price" @blur="computedFixturePrice(scope.row, scope.$index)"></el-input>
                      </template>
                      <span v-else>{{ scope.row.price || '' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="数量">
                    <template slot-scope="scope">
                      <template v-if="fixtureIndex == scope.$index">
                        <!-- <el-input
                          size="mini"
                          v-model="scope.row.qty"
                          placeholder="请输入数量"
                          @blur="computedFixturePrice(scope.row, scope.$index)"
                        ></el-input> -->
                        <checkInput v-if="!echo" :inValue.sync="scope.row.qty"
                          @inputChange="inputChange2"
                          :otherProp="[scope.row, scope.$index]"
                          :prop="{
                            type: 'number',
                            precision: 0,
                            fill: true,
                            unit: '',
                            placeholder: '',
                            integer: true,
                            range: [0, 99999999]
                          }"
                        ></checkInput>
                      </template>
                      <span v-else>{{ scope.row.qty }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="总价">
                    <template slot-scope="scope">
                      <template v-if="scope.row.price && scope.row.qty">
                        <span>{{ scope.row.price * 1 * (scope.row.qty * 1).toFixed(2) }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="说明">
                    <template slot-scope="scope">
                      <template v-if="fixtureIndex == scope.$index">
                        <el-input size="mini" v-model="scope.row.remark" placeholder="请输入说明"></el-input>
                      </template>
                      <span v-else>{{ scope.row.remark }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100" v-if="!echo">
                    <template slot-scope="scope">
                      <!-- <template v-if="fixtureIndex == scope.$index">
                        <span
                          class="jstarfont jstar-baocun finger color-blue"
                          @click="saveItem('fixture')"
                        ></span>
                        <span
                          style="margin-left: 10px"
                          class="jstarfont jstar-guanbi finger color-blue"
                          @click="cancelEdit(scope.$index)"
                        ></span>
                      </template>-->
                      <template>
                        <span
                          style="margin-right: 0px"
                          class="jstarfont jstar-xinzeng finger color-blue"
                          @click.stop="addCategotyItem(scope.$index, scope.row)"
                        ></span>
                        <!-- <span
                          class="jstarfont jstar-bianji1 finger color-blue"
                          @click="openEditItem(scope.$index, scope.row)"
                        ></span>-->
                        <el-popconfirm
                          title="确定删除改行吗？"
                          @confirm="deleteItem(fixture, scope.$index)"
                        >
                          <span
                            slot="reference"
                            style="margin-left: 10px"
                            class="jstarfont jstar-shanchutianchong finger color-blue"
                          ></span>
                        </el-popconfirm>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
                <div>
                  <el-tag style="float: right; margin: 10px 0 0 0">小计: {{ fixtureTotalPrice }} 元</el-tag>
                </div>
                <!-- <div style="margin-top: 16px" v-if="!echo">
                  <el-button type="primary" icon="el-icon-plus" @click="addItem()">添加行</el-button>
                </div>-->
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </main>
  </div>
</template>

<script>
import FileUpload from '@/components/FileUploadBom'
import FileUpload2 from '@/components/FileUpload2'
import DownLoadFiles from '@/components/DownLoadFiles'
import request from '@/api/task/index'
import localStorage from '@/utils/localStorage'
import checkInput from '@/components/checkInput'
export default {
  components: {
    FileUpload,
    DownLoadFiles,
    FileUpload2,
    checkInput
  },
  data() {
    return {
      pageLoading: false,
      loading: false,
      slaveOptions: [],
      slaveList: [],
      fixtureOptions: [],
      fixtureList: [],
      unitInfo: {
        byPart: "件",
        byPoint: "点",
        byHour: "小时",
        bySlice: "片"
      },
      baseInfo: [
        { name: '客户名称', key: 'customer' },
        { name: '报价工厂', key: 'coopFactory' },
        { name: '合作模式', key: 'coopMode' },
        { name: '是否含税', key: 'includeTax' },
        { name: '我司合作主体', key: 'coopCompany' },
        { name: '出货要求', key: 'shippingRequirement' },
        { name: '库存物料是否回购', key: 'materialRepurchase' },
        { name: '账期', key: 'accountingPeriod' },
      ],
      dataInfo: null,
      productInfo: [
        { name: '客户产品编码', key: 'productCode' },
        { name: '产品名称', key: 'productName' },
        { name: '产品类型', key: 'productType' },
        { name: '产品规格', key: 'productSpec' },
        { name: '加工工艺', key: 'process', type: 'array' },
        { name: '损耗率', key: 'wastageRate', type: 'object' },
        { name: 'PCBA拼板后尺寸', key: 'pcbaPanelSize' },
        { name: '可插件PCBA尺寸', key: 'pcbaPluggableSize' },

        { name: '客户文件', key: 'customerFile', type: 'downLoad' },
      ],
      productInputInfo: [
        // {name: "内部物料编码", key: "innerMaterialNumber", placeholder: "请输入对客户加工产品转换后的内部物料编码", mandatory: true},
        {
          name: 'PCBA拼板后尺寸',
          key: 'pcbaPanelSize',
          placeholder: '长×宽×厚mm',
        },
        {
          name: '可插件PCBA尺寸',
          key: 'pcbaPluggableSize',
          placeholder: '长×宽×厚mm',
        },
        {
          name: '物流费',
          key: 'logisticsCost',
          unit: '元/片',
          mandatory: true,
        },
        {
          name: '工程BOM文件',
          key: 'bomFile',
          type: 'upload',
          mandatory: true,
        },
      ],
      fixtureIndex: null,
      fixtureEditItem: '',
      computedTimeOut: null,
      /* 效率清单 */
      processCode: {
        CI1: "SMT",
        CI2: "DIP",
        CI3: "TEST",
        CI4: "PACK",
        CI5: "SMT编程",
        CI6: "SMT调机",
        CI7: "DIP排序",
        CI8: "TEST排序",
        CI9: "PACK排序"
      },
      processItem: [],
      processItemObj: {
        SMT: {
          projectCode: 'CI1',
          projectName: 'SMT',
          inputArgument: {
            efficiency: '',
            employeeInput: '',
            hourOutput: '',
            predictEfficiency: '',
            unit: ""
          },
        },
        DIP: {
          projectCode: 'CI2',
          projectName: 'DIP',
          inputArgument: {
            efficiency: '',
            employeeInput: '',
            hourOutput: '',
            predictEfficiency: '',
            unit: ""
          },
        },
        TEST: {
          projectCode: 'CI3',
          projectName: 'TEST',
          inputArgument: {
            efficiency: '',
            employeeInput: '',
            hourOutput: '',
            predictEfficiency: '',
            unit: ""
          },
        },
        PACK: {
          projectCode: 'CI4',
          projectName: 'PACK',
          inputArgument: {
            efficiency: '',
            employeeInput: '',
            hourOutput: '',
            predictEfficiency: '',
            unit: ""
          },
        },
      },
      machineItemMap: {
        SMT: [
          {
            projectCode: 'CI5',
            projectName: 'SMT编程',
            inputArgument: { employeeInput: '', employeeTimeCost: '' },
          },
          {
            projectCode: 'CI6',
            projectName: 'SMT调机',
            inputArgument: { employeeInput: '', employeeTimeCost: '' },
          },
        ],
        DIP: [
          {
            projectCode: 'CI7',
            projectName: 'DIP排序',
            inputArgument: { employeeInput: '', employeeTimeCost: '' },
          },
        ],
        TEST: [
          {
            projectCode: 'CI8',
            projectName: 'TEST排序',
            inputArgument: { employeeInput: '', employeeTimeCost: '' },
          },
        ],
        PACK: [
          {
            projectCode: 'CI9',
            projectName: 'PACK排序',
            inputArgument: { employeeInput: '', employeeTimeCost: '' },
          },
        ]
      },
      machineItem: [
      ],
      fixture: [],
      mapList: [
        'SMT贴片治具',
        '钢网',
        'DIP过炉治具',
        'DIP四合一治具',
        'DIP目检套板',
        'ICT治具',
        '组装辅助治具',
        '测试CPU',
        '测试显卡',
        '显示转换器',
        'U盘',
        '测试线材',
        '半成动测试治具',
        '其它',
      ],
      argumentsList: {},
      bomFileName: '',
      bomPriceFileName: '',
      AssistMaterialKey: [],
      echo: false,
      assistMaterialItem: [{}],
      toolMaterialItem: [{}],
      tableNumList: [],
      processItemUnit: ['', '', '', ''],
      processItemNum: ['', '', '', '']
    }
  },
  watch: {
    fixture: {
      deep: true,
      handler() {
        this.judgeCategoryNum()
      },
    }
  },
  async created() {
    let temp = []
    this.mapList.forEach((item, index) => {
      let tempObj = {
        category: item,
        categoryId: 'js' + index,
        code: '',
        name: '',
        price: '',
        qty: '',
        amount: '',
        remark: '',
      }
      temp.push(tempObj)
    })
    this.fixture = temp
  },
  computed: {
    machineTotalPrice: function () {
      let num = 0
      if (!this.AssistMaterialKey.length) return num
      num = this.AssistMaterialKey.reduce((pre, cur, index, arr) => {
        return this.addFloatNum(pre, cur.amount)
      }, 0)
      return num
    },
    fixtureTotalPrice: function () {
      let num = 0
      if (!this.fixture.length) return num
      num = this.fixture.reduce((pre, cur, index, arr) => {
        return this.addFloatNum(pre, cur.price * 1 * (cur.qty * 1))
      }, 0)
      return num
    },
  },
  async mounted() {
    await this.getBaseQuotation()
    if (this.processItem.length) return
    const unit = this.dataInfo.unit

    let nameUnit = {}
    let keys = Object.keys(unit)
    
    keys.forEach(item => {
      nameUnit[this.processCode[item]] = unit[item]
    })

    for (let i in nameUnit) {
      this.processItemObj[i].inputArgument.unit = this.unitInfo[nameUnit[i]]
      // if (nameUnit[i] === "bySlice") {
      //   this.processItemObj[i].inputArgument.efficiency = 1
      // }
    }

    this.dataInfo.process.forEach(item => {
      this.processItem.push(this.processItemObj[item])
      this.machineItem = this.machineItem.concat(this.machineItemMap[item])
    })
  },
  methods: {
    /* 如果是件，显示bom里的 */
    showByPartFormBom (data) {

      let nameValue = {}

      for(let item in data) {
        if (!item) continue
        nameValue[this.processCode[item]] = data[item]
      }

      this.processItem.forEach(item => {
        if (item.inputArgument.unit === '件') {
          item.inputArgument.efficiency = nameValue[item.projectName]
        }
      })
    },
    inputChange2 (data) {
      this.computedFixturePrice(data[0], data[1])
    },
    /* 检查框计算 */
    inputChange (data) {
      this.computedAsistPrice(data[0], data[1])
    },
    /* 单位小时产能 */
    inputChange3 (data) {
      data.inputArgument.hourOutput = (3600 / (data.inputArgument.efficiency * 1)).toFixed(0) * 1
      // this.computedFixturePrice(data[0], data[1])
    },
    openEdit(row, column, cell, event) {
      if (this.echo) return
      if (row.id) {
        this.fixtureOptions = [row]
      } else {
        this.fixtureOptions = []
      }
      this.fixtureIndex = row.index
    },
    deleteList() {
      this.fixtureList = []
      this.fixtureOptions = []
    },
    cancelBtn() {
      if (this.echo) {
        this.$router.push({ path: '/task/index' })
        return
      }
      this.$confirm('确定取消填写，返回上一页吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$router.push({ path: '/task/index' })
      })
    },
    addFloatNum(num1, num2) {
      var sq1, sq2, m
      try {
        sq1 = num1.toString().split('.')[1].length
      } catch (e) {
        sq1 = 0
      }
      try {
        sq2 = num2.toString().split('.')[1].length
      } catch (e) {
        sq2 = 0
      }
      m = Math.pow(10, Math.max(sq1, sq2))
      return (num1 * m + num2 * m) / m
    },
    openEditItem(index, item) {
      console.log(item)
      this.fixtureEditItem = JSON.stringify(item)
      this.fixtureIndex = index
    },
    cancelEdit(index) {
      this.fixture[index] = JSON.parse(this.fixtureEditItem)
      this.$nextTick(() => {
        this.fixtureIndex = null
      })
    },
    saveItem() {
      this.fixtureIndex = null
    },
    deleteItem(item, index) {
      item.splice(index, 1)
    },
    addItem() {
      let temp = {
        code: '',
        name: '',
        price: '',
        qty: '',
        amount: '',
        remark: '',
      }
      this.fixture.push(temp)
      // this.$forceUpdate()
      this.$nextTick(() => {
        this['fixtureEditItem'] = JSON.stringify(temp)
        this['fixtureIndex'] = this.fixture.length - 1
      })
    },
    /* 根据类添加 */
    addCategotyItem(index, item) {
      let temp = {
        category: item.category,
        categoryId: item.categoryId,
        code: '',
        name: '',
        price: '',
        qty: '',
        amount: '',
        remark: '',
      }
      this.fixture.splice(index + 1, 0, temp)
    },
    /* 合并行 */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        let num = this.tableNumList[rowIndex]
        if (num) {
          return {
            rowspan: num,
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      }
    },
    /* 判断类型数量 */
    judgeCategoryNum() {
      let list = []
      this.fixture.forEach((item, index) => {
        let num = 0
        item.index = index
        this.fixture.forEach((i) => {
          if (i.categoryId == item.categoryId) {
            num = num + 1
          }
        })
        list[index] = num
      })

      for (let i = 0; i < list.length; i++) {
        if (list[i] > 1) {
          let num = list[i] - 1
          for (let b = 0; b < num; b++) {
            list[i + b + 1] = 0
          }
          i = i + num
        }
      }
      this.tableNumList = list
    },
    remoteSlaveMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.slaveOptions = this.slaveList.filter((item) => {
            return (
              item.materialCode.toLowerCase().indexOf(query.toLowerCase()) > -1
            )
          })
        }, 200)
      } else {
        this.slaveOptions = []
      }
    },
    async remoteFixtureMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(async () => {
          await this.getFixtureList(query, this.$route.query.id)
          this.loading = false
          this.fixtureOptions = this.fixtureList.filter((item) => {
            return item.materialNumber.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        }, 500)
      } else {
        this.fixtureOptions = []
      }
    },
    computedTotalPrice(item, index) {
      // let keys = Object.keys(item.argument)
      for (let key of item.arguments) {
        if (!item.argumentsValue[key.name]) return
      }
      if (this.computedTimeOut) {
        clearTimeout(this.computedTimeOut)
      }
      this.computedTimeOut = setTimeout(async () => {
        clearTimeout(this.computedTimeOut)
        let temp = JSON.parse(JSON.stringify(item))
        temp.calcValue = await this.calcValue(item)
        // this.$set(this.projectData.machine, index, temp)
      }, 200)
    },
    /* 计算工程开机费 */
    calcValue(item) {
      return new Promise((resolve, reject) => {
        let params = {
          arguments: item.argumentsValue,
        }
        this.$quote
          .calcValue(item.expenseItemId, params)
          .then((res) => {
            if (res.code == 200) {
              resolve(res.data)
            } else {
              this.$message.error(res.code + '-' + res.msg)
              resolve(0)
            }
          })
          .catch((err) => {
            reject(0)
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    /* 上传文件 */
    uploadFile(files) {
      this.showByPartFormBom(files.id.data)
      this.dataInfo.bomFile = files.id.id
      this.bomFileName = files.file.name
    },
    /* 获取工程报价基本信息 */
    getBaseQuotation() {
      this.pageLoading = true
      return new Promise((resolve) => {
        this.$quote
          .getUpcomingTaskById(this.$route.query.id)
          .then((res) => {
            this.pageLoading = false
            if (res.code == 200) {
              if (res.data.data.logisticsChargeType != 2) {
                this.productInputInfo.splice(2, 1)
              }
              res.data.data.assistMaterialItem.forEach(item => {
                item.amount = 0
              })

              /* 后端改了，耦合太多，前端该回去 */
              let temp = []
              res.data.data.process.forEach(it => {
                temp.push(this.processCode[it])
              })

              res.data.data.process = temp
              this.dataInfo = res.data.data
              if (res.data.data.dataSource) {
                this.echo = true
                this.reviewData(res.data.data.dataSource)
              }
              
              this.setDataInfo()
              this.$nextTick(() => {
                this.dataInfo.assistMaterialItem.forEach((item) => {
                  if (item.amount) {
                    this.AssistMaterialKey.push(item)
                    this.$refs.fixtureMultipleTable.toggleRowSelection(
                      item,
                      true
                    )
                  }
                })
              })
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }

            resolve()
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    /* 回显 */
    reviewData(data) {
      data.processItem.forEach(item => {
        item.projectName = this.processCode[item.projectCode]
      })

      // console.log(data.machineItem)
      data.machineItem.forEach(item => {
        item.projectName = this.processCode[item.projectCode]
      })

      this.processItem = data.processItem
      this.machineItem = data.machineItem
      this.dataInfo.assistMaterialItem = data.assistMaterialItem
      this.fixture = data.toolMaterialItem
    },
    /* 表格选中改变 */
    handleSelect(data, row) {
      for (let v of data) {
        v.select = true
      }

      const selectData = data.find(it => it.materialNumber == row.materialNumber)
      if (!selectData) {
        row.select = false
      }


      this.AssistMaterialKey = data
    },
    /* 查询工治具 */
    getFixtureList(name, id) {
      let objFixtureEditItem = JSON.parse(this.fixtureEditItem)
      return new Promise((resolve) => {
        this.$params
          .getToolMaterial({ps: 10, pn: 1, materialNumber_like_right: name, usrOrg: id})
          .then((res) => {
            if (res.code == 200) {
              res.data.rows.forEach((item) => {
                item.category = objFixtureEditItem.category
                item.categoryId = objFixtureEditItem.categoryId
              })
              this.fixtureList = res.data.rows
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            resolve()
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    /* 计算工治具 */
    computedFixturePrice(item, index) {
      console.log(item, index)
    },
    /* 计算辅料 */
    computedAsistPrice(item, index) {
      console.log(item)
      if (!item.price || !item.materialUse) return 0
      if (!item.capacityVolume) return 0
      item.amount = ((item.price * 100000) * (item.materialUse * 100) / ((item.capacityVolume || 1)) / 100000 / 100).toFixed(2)
    },
    /* 提交客户报价 */
    submitForm() {
      if (JSON.stringify(this.dataInfo.bomFile) == '{}') {
        this.$message.error('请先上传BOM文件')
        return
      }

      // if (!this.dataInfo.innerMaterialNumber) {
      //   this.$message.error("请填写物流编码")
      //   return
      // }

      if (this.dataInfo.logisticsChargeType == 2) {
        if (!this.dataInfo.logisticsCost) {
          this.$message.error("请先物流费")
          return
        }
      }

      for (let item of this.AssistMaterialKey) {
        if (item.price != 0 && !item.price) {
          this.$message.error(`辅料-${item.materialName}的价格为空`)
          return
        }
      }

      for (let item of this.fixture) {
        if (item.price != 0 && !item.price) {
          this.$message.error(`工治具-${item.name}的价格为空`)
          return
        }
      }

      for (let item of this.processItem) {
        for (let i in item.inputArgument) {
          if (!item.inputArgument[i]) {
            this.$message.error(`请将效率清单填写完整`)
            return
          }
        }
      }

      for (let item of this.machineItem) {
        for (let i in item.inputArgument) {
          if (!item.inputArgument[i]) {
            this.$message.error(`请将工程开机费填写完整`)
            return
          }
        }
      }

      this.pageLoading = true
      this.dataInfo.processItem = this.processItem
      this.dataInfo.machineItem = this.machineItem
      this.dataInfo.toolMaterialItem = this.fixture

      let params = JSON.parse(JSON.stringify(this.dataInfo))

      params.processItem.forEach((item) => {
        delete item.projectName
      })

      params.machineItem.forEach((item) => {
        delete item.projectName
      })

      params.assistMaterialItem = this.AssistMaterialKey

      const endParams = {
        bomFile: params.bomFile,
        innerMaterialNumber: params.innerMaterialNumber,
        logisticsCost: params.logisticsCost,
        pcbaPanelSize: params.pcbaPanelSize,
        pcbaPluggableSize: params.pcbaPluggableSize,
        processItem: params.processItem,
        machineItem: params.machineItem,
        assistMaterialItem: params.assistMaterialItem,
        toolMaterialItem: params.toolMaterialItem,
      }

      // console.log(endParams)

      request
        .putUpcomingTask(this.$route.query.id, endParams)
        .then((res) => {
          this.pageLoading = false
          if (res.code == 200) {
            this.$message.success('提交成功！')
            this.echo = true
            localStorage.remove('projectData')
            this.$router.push({ path: '/task/index' })
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch((err) => {
          this.$message.error(JSON.stringify(err))
        })
    },
    /* 暂存 */
    tempStore() {
      this.dataInfo.processItem = this.processItem
      this.dataInfo.machineItem = this.machineItem
      this.dataInfo.toolMaterialItem = this.fixture
      localStorage.set('projectData', {
        id: this.$route.query.id,
        data: this.dataInfo,
      })
    },
    /* 恢复暂存值 */
    setDataInfo() {
      const tempStoreData = localStorage.get('projectData')
      if (!tempStoreData) return
      if (tempStoreData.id != this.$route.query.id) return
      let tempData = localStorage.get('projectData').data
      this.dataInfo = tempData
      console.log(tempData)
      this.processItem = this.dataInfo.processItem
      this.machineItem = this.dataInfo.machineItem
      this.fixture = this.dataInfo.toolMaterialItem || []
    },
    /* 过滤属性 */
    filterData(data) {
      if (!data.bomFile) return 'BOM文件未上传！'
      let indexArr = []
      data.slaveMaterial.forEach((item, index) => {
        if (!item.materialCode) {
          indexArr.push(index)
        }
      })
      indexArr.forEach((item) => {
        data.slaveMaterial.splice(item, 1)
      })

      let indexArr2 = []
      data.fixture.forEach((item, index) => {
        if (!item.materialCode) {
          indexArr2.push(index)
        }
      })
      indexArr2.forEach((item) => {
        data.fixture.splice(item, 1)
      })
      return false
    },
  },
}
</script>

<style lang="less">
.projectQuote {
  width: 100%;
  height: calc(100vh - 84px);
  box-sizing: border-box;
  padding: 16px;
  background-color: #f3f5fa;
  overflow: auto;
  .cell{
    // min-height: 47px;
  }
  .setred::before {
    content: '*';
    position: relative;
    top: 4px;
    left: -5px;
    color: red;
    font-weight: bold;
    font-size: 16px;
  }
  header {
    height: 50px;
    background-color: white;
    color: #666666;
    .blueLine {
      margin-left: 5px;
      height: 20px;
      width: 5px;
      background-color: #246cff;
    }
  }
  main {
    margin-top: 20px;
    height: calc(100% - 70px);
    overflow: auto;
    .el-descriptions--medium:not(.is-bordered) th,
    .el-descriptions--medium:not(.is-bordered) td {
      padding-bottom: 20px;
    }
    .el-table {
      .el-table__header-wrapper {
        th {
          padding-bottom: 10px;
          // background-color: #1890ff;
          // color: white;
        }
      }
      .el-table__row {
        td {
          padding-bottom: 10px;
        }
      }
    }
    .demandIdBox {
      height: 36px;
      line-height: 36px;
      text-indent: 20px;
      background-color: white;
      color: #666666;
    }
    .infoBox {
      box-sizing: border-box;
      padding: 16px 20px;
      margin-top: 20px;
      background-color: white;
    }
    .el-descriptions-item__label {
      color: rgb(151, 151, 151);
      align-items: center;
    }
    .donwLoadBox {
      a {
        color: #3377ff;
      }
    }
  }
  .contentClass {
    box-sizing: border-box;
    padding: 0 16px;
  }
  .bottomBtnBox {
    height: 66px;
    border-top: 1px solid rgb(240, 240, 240);
    .el-button {
      margin: 10px 20px 0;
    }
  }
  .totalPriceBox {
    width: 1200px;
    height: 50px;
    justify-content: end;
  }
  .fixtureLeft {
    width: 15%;
    div {
      height: 45px;
      border: 1px solid #dfe6ec;
      border-top: none;
      text-align: center;
      line-height: 45px;
      margin-right: 20px;
      box-sizing: border-box;
    }
    & > div:nth-child(1) {
      border-top: 1px solid #dfe6ec;
      background-color: #46a6ff;
      border-color: #46a6ff;
      color: #fff;
    }
  }
  .fixtureRight {
    input {
      height: 100%;
      width: 100%;
      border: unset;
      background-color: unset;
      font-size: 14px;
      padding: 0;
    }
  }
  .labelWidth {
    min-width: 200px;
    text-align: end;
  }
}
</style>